package com.cwc.ueditor.controller;

import com.alibaba.fastjson.JSONObject;
import com.cwc.ueditor.entity.ImgFile;
import com.cwc.ueditor.service.FileOperationService;
import com.cwc.ueditor.util.Base64MultipartFile;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @author wxhntmy
 */
@RestController
public class UEditorController {

    @Resource
    private FileOperationService fileOperationService;

    /**
     * UEditor 后端配置文件
     */
    private String config_json = "{\n" +
            "\t\"imageActionName\": \"uploadimage\",\n" +
            "\t\"imageFieldName\": \"upfile\",\n" +
            "\t\"imageMaxSize\": 2048000,\n" +
            "\t\"imageAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"],\n" +
            "\t\"imageCompressEnable\": true,\n" +
            "\t\"imageCompressBorder\": 1600,\n" +
            "\t\"imageInsertAlign\": \"none\",\n" +
            "\t\"imageUrlPrefix\": \"\",\n" +
            "\t\"imagePathFormat\": \"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
            "\n" +
            "\t\"scrawlActionName\": \"uploadscrawl\",\n" +
            "\t\"scrawlFieldName\": \"upfile\",\n" +
            "\t\"scrawlPathFormat\": \"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
            "\t\"scrawlMaxSize\": 2048000,\n" +
            "\t\"scrawlUrlPrefix\": \"\",\n" +
            "\t\"scrawlInsertAlign\": \"none\",\n" +
            "\n" +
            "\t\"snapscreenActionName\": \"uploadimage\",\n" +
            "\t\"snapscreenPathFormat\": \"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
            "\t\"snapscreenUrlPrefix\": \"\",\n" +
            "\t\"snapscreenInsertAlign\": \"none\",\n" +
            "\n" +
            "\t\"catcherLocalDomain\": [\"127.0.0.1\", \"localhost\", \"img.baidu.com\"],\n" +
            "\t\"catcherActionName\": \"catchimage\",\n" +
            "\t\"catcherFieldName\": \"source\",\n" +
            "\t\"catcherPathFormat\": \"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
            "\t\"catcherUrlPrefix\": \"\",\n" +
            "\t\"catcherMaxSize\": 2048000,\n" +
            "\t\"catcherAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"],\n" +
            "\n" +
            "\t\"videoActionName\": \"uploadvideo\",\n" +
            "\t\"videoFieldName\": \"upfile\",\n" +
            "\t\"videoPathFormat\": \"/ueditor/jsp/upload/video/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
            "\t\"videoUrlPrefix\": \"\",\n" +
            "\t\"videoMaxSize\": 102400000,\n" +
            "\t\"videoAllowFiles\": [\n" +
            "\t\t\".flv\", \".swf\", \".mkv\", \".avi\", \".rm\", \".rmvb\", \".mpeg\", \".mpg\",\n" +
            "\t\t\".ogg\", \".ogv\", \".mov\", \".wmv\", \".mp4\", \".webm\", \".mp3\", \".wav\", \".mid\"\n" +
            "\t],\n" +
            "\n" +
            "\t\"fileActionName\": \"uploadfile\",\n" +
            "\t\"fileFieldName\": \"upfile\",\n" +
            "\t\"filePathFormat\": \"/ueditor/jsp/upload/file/{yyyy}{mm}{dd}/{time}{rand:6}\",\n" +
            "\t\"fileUrlPrefix\": \"\",\n" +
            "\t\"fileMaxSize\": 51200000,\n" +
            "\t\"fileAllowFiles\": [\n" +
            "\t\t\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\",\n" +
            "\t\t\".flv\", \".swf\", \".mkv\", \".avi\", \".rm\", \".rmvb\", \".mpeg\", \".mpg\",\n" +
            "\t\t\".ogg\", \".ogv\", \".mov\", \".wmv\", \".mp4\", \".webm\", \".mp3\", \".wav\", \".mid\",\n" +
            "\t\t\".rar\", \".zip\", \".tar\", \".gz\", \".7z\", \".bz2\", \".cab\", \".iso\",\n" +
            "\t\t\".doc\", \".docx\", \".xls\", \".xlsx\", \".ppt\", \".pptx\", \".pdf\", \".txt\", \".md\", \".xml\"\n" +
            "\t],\n" +
            "\n" +
            "\t\"imageManagerActionName\": \"listimage\",\n" +
            "\t\"imageManagerListPath\": \"/ueditor/jsp/upload/image/\",\n" +
            "\t\"imageManagerListSize\": 20,\n" +
            "\t\"imageManagerUrlPrefix\": \"\",\n" +
            "\t\"imageManagerInsertAlign\": \"none\",\n" +
            "\t\"imageManagerAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"],\n" +
            "\n" +
            "\t\"fileManagerActionName\": \"listfile\",\n" +
            "\t\"fileManagerListPath\": \"/ueditor/jsp/upload/file/\",\n" +
            "\t\"fileManagerUrlPrefix\": \"\",\n" +
            "\t\"fileManagerListSize\": 20,\n" +
            "\t\"fileManagerAllowFiles\": [\n" +
            "\t\t\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\",\n" +
            "\t\t\".flv\", \".swf\", \".mkv\", \".avi\", \".rm\", \".rmvb\", \".mpeg\", \".mpg\",\n" +
            "\t\t\".ogg\", \".ogv\", \".mov\", \".wmv\", \".mp4\", \".webm\", \".mp3\", \".wav\", \".mid\",\n" +
            "\t\t\".rar\", \".zip\", \".tar\", \".gz\", \".7z\", \".bz2\", \".cab\", \".iso\",\n" +
            "\t\t\".doc\", \".docx\", \".xls\", \".xlsx\", \".ppt\", \".pptx\", \".pdf\", \".txt\", \".md\", \".xml\"\n" +
            "\t]\n" +
            "\n" +
            "}";

    /**
     * 响应后台配置 GET 请求
     * @param action 请求类型
     * @return 响应json
     */
    @RequestMapping(value = "/ueditor/action", method = RequestMethod.GET )
    public Object action(String action){

        System.out.println("action: " + action);

        JSONObject jsonObject = JSONObject.parseObject(config_json);

        return jsonObject;
    }

    /**
     * 图片、文件、视频
     * 执行单个文件上传操作
     * uploadimage、uploadvideo、uploadfile
     * @param upfile 文件数据
     * @return 响应json
     */
    @RequestMapping(value = "/ueditor/action", method = RequestMethod.POST )
    public Object action_upload(MultipartFile upfile){

        System.out.println("upfile: " + upfile.getOriginalFilename());

        String filename = upfile.getOriginalFilename();
        String uuid = UUID.randomUUID().toString();
        boolean boole = fileOperationService.saveFile(upfile, uuid);

        Map<String, String> map = new HashMap<>();
        if (boole) {
            map.put("state", "SUCCESS");
            map.put("url","/ueditor/download/"+uuid+"/"+filename);
        } else {
            map.put("state", "FAIL");
            map.put("url","");
        }
        map.put("title", filename);
        map.put("original", filename);
        return map;
    }

    /**
     * 执行涂鸦照片文件上传操作
     * uploadscrawl
     * @param action
     * @param upfile 文件数据
     * @return 响应json
     */
    @RequestMapping(value = "/ueditor/uploadscrawl", method = RequestMethod.POST )
    public Object uploadscrawl(String action, String upfile){

        System.out.println("uploadscrawl action: " + action);
        System.out.println("upfile: " + upfile);

        upfile = "data:image/jpg;base64," + upfile;

        System.out.println("base64 upfile: " + upfile);

        Map<String, String> map = new HashMap<>();
        String filename = String.valueOf(System.currentTimeMillis());
        filename += ".jpg";

        MultipartFile multipartFile = base64toMultipart(upfile, filename);

        String uuid = UUID.randomUUID().toString();
        boolean boole = fileOperationService.saveFile(multipartFile, uuid);

        if (boole) {
            map.put("state", "SUCCESS");
            map.put("url","/ueditor/download/"+uuid+"/"+filename);
        } else {
            map.put("state", "FAIL");
            map.put("url","");
        }
        map.put("title", filename);
        map.put("original", filename);
        return map;
    }

    /**
     * 获取在线图片列表
     * 响应 listimage GET请求
     * @param action 请求类型
     * @param start 开始下标
     * @param size 请求图片列表长度
     * @return 响应json
     */
    @RequestMapping(value = "/ueditor/listimage", method = RequestMethod.GET )
    public Object listimage_action(String action, int start, int size){

        System.out.println("listimage action: " + action);
        System.out.println("start: " + start);
        System.out.println("size: " + size);

        Map<String, Object> list_map = fileOperationService.getAllImgFiles(start, size);

        List<ImgFile> list_img_files = (List<ImgFile>) list_map.get("list");

        Map<String, Object> map = new HashMap<>();
        map.put("state", "SUCCESS");

        List<Map> list = new ArrayList<>();

        for (int i = 0; i < list_img_files.size(); i++) {
            Map<String, Object> map1 = new HashMap<>();
            String uuid = list_img_files.get(i).getUuid();
            map1.put("url", "/ueditor/download/"+uuid+"/"+list_img_files.get(i).getFileName());
            list.add(map1);
        }

        map.put("list",list);
        map.put("start", start);
        map.put("total", list_map.get("num"));


        return map;
    }

    /**
     * 获取在线文件列表
     * 响应 listfile GET请求
     * @param action 请求类型
     * @param start 开始下标
     * @param size 请求文件列表长度
     * @return 响应json
     */
    @RequestMapping(value = "/ueditor/listfile", method = RequestMethod.GET )
    public Object listfile_action(String action, int start, int size){

        System.out.println("listfile action: " + action);
        System.out.println("start: " + start);
        System.out.println("size: " + size);

        Map<String, Object> list_map = fileOperationService.getAllFiles(start, size);

        List<ImgFile> list_img_files = (List<ImgFile>) list_map.get("list");

        Map<String, Object> map = new HashMap<>();
        map.put("state", "SUCCESS");

        List<Map> list = new ArrayList<>();

        for (int i = 0; i < list_img_files.size(); i++) {
            Map<String, Object> map1 = new HashMap<>();
            String uuid = list_img_files.get(i).getUuid();
            map1.put("url", "/ueditor/download/"+uuid+"/"+list_img_files.get(i).getFileName());
            map1.put("title", list_img_files.get(i).getFileName());
            map1.put("original", list_img_files.get(i).getFileName());
            list.add(map1);
        }

        map.put("list",list);
        map.put("start", start);
        map.put("total", list_map.get("num"));


        return map;
    }

    /**
     * 下载文件
     * @param uuid
     * @param request
     * @param response
     */
    @RequestMapping(value = "/ueditor/download/{uuid}/{filename}",method = {RequestMethod.POST, RequestMethod.GET})
    public void download(@PathVariable String uuid,@PathVariable String filename,
                             HttpServletRequest request,
                             HttpServletResponse response){

        System.out.println("uuid: " + uuid);
        System.out.println("filename: " + filename);
        fileOperationService.download(uuid, request, response);
    }

    /**
     * Base64转化为MultipartFile
     * @param data 前台传过来base64的编码
     * @param fileName 图片的文件名
     * @return
     */
    public MultipartFile base64toMultipart(String data, String fileName) {
        try {
            String[] baseStrs = data.split(",");
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] b = decoder.decodeBuffer(baseStrs[1]);
            for(int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            return new Base64MultipartFile(b, baseStrs[0] , fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
